//
//  RegisterViewController.m
//  seer
//
//  Created by Lin Eidan on 14-5-28.
//  Copyright (c) 2014年 haomee. All rights reserved.
//

#import "RegisterViewController.h"
#import "Header.h"
#import "config.h"
#import "PasswordViewController.h"
#import "PersonalInfoViewController.h"

@interface RegisterViewController ()

@property (strong, nonatomic) IBOutlet UIView *navBarView;
@property (strong, nonatomic) IBOutlet UILabel *titleLabel;
@property (strong, nonatomic) IBOutlet UITextField *phoneField;
@property (strong, nonatomic) IBOutlet UIButton *getCodeBtn;

@property (strong, nonatomic) NSString *phoneNum;
@property (strong, nonatomic) NSString *getCodeSuccessAndReturnAk;

//input code
@property (strong, nonatomic) IBOutlet UIView *inputCodeBgView;
@property (strong, nonatomic) IBOutlet UITextField *codeField;
@property (strong, nonatomic) IBOutlet UIButton *goNextBtn;

@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.isFromForgetPassword = NO;
        self.isFromThirdLogin = NO;
        self.isFromeChangePhone = NO;
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self drawNavTopContentView:self.navBarView];
    
    self.inputCodeBgView.alpha = 0;
    self.goNextBtn.alpha = 0;
    if (self.isFromThirdLogin) {
        self.titleLabel.text = @"绑定手机号";
    }
    if (self.isFromForgetPassword) {
        self.titleLabel.text = @"忘记密码";
    }
    if (self.isFromeChangePhone) {
        self.titleLabel.text = @"更换手机号";
    }
    // Do any additional setup after loading the view from its nib.
}


#pragma -mark xib click
- (IBAction)getCode:(id)sender {
    if (![Common checkPhoneLegal:self.phoneField.text]) {
        [PopTips tipsAtTop:self.view Msg:NotifyInvalidPhone];
        return;
    }
    
    self.getCodeBtn.enabled = NO;
    self.phoneNum = self.phoneField.text;
    UserObj *obj = [UserObj sharedInstance];
    
    NSString *ak = [Common md5:[Common md5:self.phoneNum]];
    NSString *url = [NSString stringWithFormat:@"%@phoneRegSdCode&mobile=%@&ak=%@",API_BASE,self.phoneNum,ak];
    
    if (self.isFromThirdLogin) {
        url = [NSString stringWithFormat:@"%@pfBindPhoneSdCode&mobile=%@&ak=%@&pf_type=%@&pf_id=%@",API_BASE,self.phoneNum,ak,obj.thridPlatform,obj.thridPlatformID];
    }
    
    if (self.isFromForgetPassword) {
        url = [NSString stringWithFormat:@"%@ForgetPwdSdCode&mobile=%@&ak=%@",API_BASE,self.phoneNum,ak];
    }
    
    [kApp displayWaitViewWithAllMaskView:NO];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        [self.getCodeBtn setTitle:@"重新获取验证码" forState:UIControlStateNormal];
        [self performSelector:@selector(delayToHandleGetCodeBtnEnable) withObject:nil afterDelay:5];
        [kApp hideWaitView];
        if (isSuccess) {
            NSDictionary *dic = responseObj;
            int flag = [[dic objectForKey:@"flag"] intValue];
            NSLog(@"%d",flag);
            if (1 == flag) {
                
                self.getCodeSuccessAndReturnAk = [dic objectForKey:@"ak"];
                [UIView animateWithDuration:0.2 animations:^{
                    self.inputCodeBgView.alpha = 1;
                    self.goNextBtn.alpha = 1;
                    self.getCodeBtn.top = self.goNextBtn.top;
                }];
                
            }else if (2 == flag){
                [PopTips tipsAtTop:self.view Msg:NotifyGetCodeInvalid];
            }else if (3 == flag){
                if (self.isFromThirdLogin) {
                    [PopTips tipsAtTop:self.view Msg:NotifyPhoneHasBind];
                    return;
                }
                if (self.isFromForgetPassword) {
                    [PopTips tipsAtTop:self.view Msg:NotifyPhoneNotRegister];
                    return;
                }
                [PopTips tipsAtTop:self.view Msg:NotifyPhoneHasRegister];
            }else if (0 == flag){
                [PopTips tipsAtTop:self.view Msg:NotifyGetCodeInvalid];
            }else if (-1 == flag){
                [PopTips tipsAtTop:self.view Msg:NotifyGetCodeTooMany];
            }
        }else{
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
        }
        
    }];
    
}

-(void)delayToHandleGetCodeBtnEnable{
    self.getCodeBtn.enabled = YES;
}
- (IBAction)goNext:(id)sender {
    NSString *url = [NSString stringWithFormat:@"%@checkAuthCode&mobile=%@&ak=%@&code=%@",API_BASE,self.phoneNum,self.getCodeSuccessAndReturnAk,self.codeField.text];
    [kApp displayWaitViewWithAllMaskView:NO];
    [[AFGetData sharedInstance] startGet:url andResultIsJSON:YES andRequestCompletion:^(id responseObj, BOOL isSuccess) {
        [kApp hideWaitView];
        if (isSuccess) {
            NSDictionary *dic = responseObj;
            int flag1 = [[dic objectForKey:@"flag"] intValue];
            if (1 == flag1) {
                if (self.isFromThirdLogin) {  //第三方登录，需要绑定手机，验证码正确后，开始绑定,需要输入密码。
                    UserObj *obj = [UserObj sharedInstance];
                    NSString *newURL = [NSString stringWithFormat:@"%@pfBindPhone",API_BASE];
                    NSString *ak = [Common md5:[NSString stringWithFormat:@"%@%@%@",obj.thridPlatform,obj.thridPlatformID,self.phoneNum]];
                    NSDictionary *dic = @{@"pf_type": obj.thridPlatform,@"pf_id":obj.thridPlatformID,@"mobile":self.phoneNum,@"nickname":obj.thridAccountName,@"ak":ak};
                    [[AFGetData sharedInstance] startPost:newURL andInfo:dic andDataBodyBlock:^(id<AFMultipartFormData> formData) {
                        
                    } andRequestCompletion:^(id responseObj, BOOL isSuccess) {
                        if (isSuccess) {
                            if (!responseObj) {
                                [PopTips tipsAtTop:self.view Msg:NotifyBindFaild];
                                return ;
                            }
                            int flag = [[responseObj objectForKey:@"flag"] intValue];
                            BOOL needPwd = [[responseObj objectForKey:@"needPwd"] boolValue];
                            if (1 == flag) {
                                NSDictionary *userInfo = [responseObj objectForKey:@"user"];
                                obj.uid = [userInfo objectForKey:@"uid"];
                                obj.accessKey = [userInfo objectForKey:@"accesskey"];
                                obj.phoneNum = self.phoneNum;
                                obj.campId = [userInfo objectForKey:@"camp_id"];
                                obj.campPicSrc = [userInfo objectForKey:@"camp_pic"];
                                obj.headPicSrc = [userInfo objectForKey:@"head_pic"];
                                obj.qqId = [userInfo objectForKey:@"qq_id"];
                                obj.qqNickName = [userInfo objectForKey:@"qq_nickname"];
                                obj.sinaId = [userInfo objectForKey:@"sinawb_id"];
                                obj.sinaNickName = [userInfo objectForKey:@"sinawb_nickname"];
                                obj.username = [userInfo objectForKey:@"username"];
                                
                                //绑定成功后，这边后台需要返回一个标志位，需不需要设置密码，应该是如果这个手机号已经提前注册过，已经设置密码了，就不需要设置密码，如果手机号还没有注册过，就需要设置密码。
                                
                                //是否需要密码
                                if (needPwd) {
                                    //需要输入密码
                                    PasswordViewController *passwordVC = [[PasswordViewController alloc] initWithNibName:@"PasswordViewController" bundle:nil];
                                    passwordVC.phoneNum = self.phoneNum;
                                    passwordVC.isFromThirdLogin= self.isFromThirdLogin;
                                    [self.navigationController pushViewController:passwordVC animated:YES];
                                }else{
                                    //绑定成功后，进入编辑页面。
                                    PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithNibName:@"PersonalInfoViewController" bundle:nil];
                                    personalInfoVC.firstRegisterToGoTo = YES;
                                    [self.navigationController pushViewController:personalInfoVC animated:YES];
                                }
                                
                                [obj saveUserToLocal];
                                
                            }else if (3 == flag){
                                [PopTips tipsAtTop:self.view Msg:NotifyPhoneHasBind];
                            }else{
                                [PopTips tipsAtTop:self.view Msg:NotifyBindFaild];
                            }
                        }else{
                            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
                        }
                        
                    }];
                    
                    return;
                }
                
                //是从个人编辑页面的更改号码过来的。
                if (self.isFromeChangePhone) {
                    [self goBack:nil];
                    if ([self.navigationController.topViewController isKindOfClass:[PersonalInfoViewController class]]) {
                        PersonalInfoViewController *personInfoVC = (PersonalInfoViewController *)self.navigationController.topViewController;
                        [personInfoVC changePhoneWithPhoneNum:self.phoneNum];
                    }
                    return;
                }
                
                //手机号注册，和忘记密码之后的 密码设置。
                PasswordViewController *passwordVC = [[PasswordViewController alloc] initWithNibName:@"PasswordViewController" bundle:nil];
                passwordVC.phoneNum = self.phoneNum;
                passwordVC.isResetPassword = self.isFromForgetPassword;
                [self.navigationController pushViewController:passwordVC animated:YES];
            }else{
                [PopTips tipsAtTop:self.view Msg:NotifyCheckCodeFailed];
            }
        }else{
            [[kHandle sharedInstance] showTipsWhenRequestFailedWithView:self.view];
        }
        
    }];
    
    
}

- (IBAction)goBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
		if ([obj isKindOfClass:[UITextField class]]) {
			[obj resignFirstResponder];
		}
	}];
    [self.inputCodeBgView.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
		if ([obj isKindOfClass:[UITextField class]]) {
			[obj resignFirstResponder];
		}
	}];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
